<template>
  <div class="conversion">
    <div class="conversion-form-field">
      <el-row :gutter="10">
        <el-col :span="5" class="status">
          <div class="grid-content bg-purple" @click="writeCounter++">
            <label for="needUpdate">需要更新:</label>
            <el-select
              v-model="searchData.needUpdate"
              name="needUpdate"
              placeholder="所有"
              clearable
              size="medium"
              popper-class="b-select"
            >
              <el-option value="1" label="是" />
              <el-option value="0" label="否" />
            </el-select>
          </div>
        </el-col>
        <!-- <el-col :span="5" class="status">
          <div class="grid-content bg-purple">
            <label for="sortMode">排序字段:</label>
            <el-select
              v-model="searchData.sortField"
              name="sortMode"
              placeholder="所有"
              clearable
              size="medium"
              popper-class="b-select"
            >
              <el-option value="0" label="日期" />
              <el-option value="1" label="产品" />
              <el-option value="2" label="颜色" />
            </el-select>
          </div>
        </el-col>
        <el-col :span="5" class="status">
          <div class="grid-content bg-purple">
            <label for="sortMode">排序方式:</label>
            <el-select
              v-model="searchData.sortord"
              name="sortMode"
              placeholder="所有"
              clearable
              size="medium"
              popper-class="b-select"
            >
              <el-option value="1" label="升序" />
              <el-option value="0" label="降序" />
            </el-select>
          </div>
        </el-col> -->
        <!-- <el-col :span="8" class="update-time">
          <label for="updateTime">更新时间:</label>
          <el-date-picker
            v-model="searchData.updateTime"
            name="updateTime"
            type="daterange"
            size="medium"
            range-separator="-"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-col> -->
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <label for="product">产品名称:</label>
            <el-select
              v-model="searchData.productName"
              name="product"
              placeholder="请选择产品(可多选)"
              multiple
              filterable
              clearable
              default-first-option
              no-match-text="不存在该选项"
              size="medium"
              popper-class="b-select"
            >
              <el-option
                v-for="productItem in productOptions"
                :key="productItem.productName"
                :label="productItem.productName"
                :value="productItem.productName"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <label for="color">产品颜色:</label>
            <el-select
              v-model="searchData.colorIds"
              name="color"
              placeholder="请选择颜色(可多选)"
              multiple
              filterable
              clearable
              default-first-option
              no-match-text="不存在该选项"
              size="medium"
              popper-class="b-select"
            >
              <el-option
                v-for="colorItem in colorOptions"
                :key="colorItem.id"
                :label="colorItem.color"
                :value="colorItem.id"
                seletced
              />
            </el-select>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-button type="primary" size="small" @click="search">查询</el-button>
          <el-button size="small" @click="counter++">重置</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="conversion-table">
      <el-table
        :data="productData"
        empty-text="暂无数据!"
        style="width: 100%"
        table-layout="fixed"
        stripe
      >
        <el-table-column align="center" prop="productName" label="产品" width="260">
          <template #default="scope">
            <el-tag effect="light">{{ scope.row.productName }} - {{ scope.row.color.color }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="productModel" label="型号" min-width="100" />
        <el-table-column align="center" prop="tradeMark" label="商标" min-width="100" />
        <el-table-column align="center" label="重量换算个数 (kg)" width="180">
          <template #default="scope">
            <el-input v-model="scope.row.weight" class="w-50 m-2 weight-input" size="small" placeholder="请输入重量" @keyup.enter.native="weightToNumber(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="个数换算重量(个)" width="180">
          <template #default="scope">
            <el-input v-model="scope.row.number" class="w-50 m-2 number-input" size="small" placeholder="请输入个数" @keyup.enter.native="numberToWeight(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="singleWeight" label="单个克数(克)" width="160">
          <template #default="scope">
            <!-- <el-input v-model="scope.row.singleWeight" class="w-50 m-2 number-input" size="small" placeholder="请输入单个重量" @keyup.enter.native="updatesingleWeight(scope.row)" @blur="updatesingleWeight(scope.row)" /> -->
            <el-input v-if="hasWritePermission" v-model="scope.row.singleWeight" class="w-50 m-2 number-input" size="small" placeholder="请输入单个重量" @keyup.enter.native="updatesingleWeight(scope.row)" @blur="updatesingleWeight(scope.row)" />
            <div v-if="!hasWritePermission">
              {{ scope.row.singleWeight }} g
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="oneBoxWeight" label="每盆大约重量(kg)" width="160">
          <template #default="scope">
            {{ scope.row.oneBoxWeight }} kg
          </template>
        </el-table-column>
        <el-table-column align="center" prop="oneBoxNumber" label="每盆大约个数(个)" width="160">
          <template #default="scope">
            约 {{ scope.row.oneBoxNumber }} 个/盆
          </template>
        </el-table-column>
        <el-table-column align="center" prop="updatedAt" label="围数日期" width="100">
          <template #default="scope">
            <div>
              {{ moment(scope.row.updatedAt).format('YYYY-MM-DD HH:mm:ss') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="operatorUser" label="围数人" min-width="90" />
        <el-table-column align="center" label="操作" min-width="110">
          <template #default="scope">
            <el-button v-if="hasAdminPermission" type="primary" plain size="small" @click="updateHandle(scope.row)">出仓围数</el-button>
            <!-- <el-button type="danger" plain size="small" @click="deleteHandle(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <el-row :gutter="24" justify="center" align="middle" type="flex" class="page-row">
        <el-col :span="10">
          <el-pagination
            layout="total, sizes, prev, pager, next"
            :current-page="page"
            :page-size="size"
            :total="total"
            :page-sizes="[1, 5, 10, 15, 20, 30, 40, 50, 100]"
            background
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import { getProductList, getProductsOptionsList, updateProduct } from '@/api/product'
import { getColorList } from '@/api/color'
import { adminPermissionTime } from '@/config/config'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      // 表单区域数据
      searchData: {},
      productOptions: [],
      colorOptions: [],

      // 表格区域数据
      productData: [],
      counter: 0,
      timeoutId: null,
      permissionTimeoutId: null,
      hasAdminPermission: false,
      // 单独写入单重数据权限相关数据
      writeCounter: 0,
      writeTimeoutId: null,
      writePermissionTimeoutId: null,
      hasWritePermission: false,
      page: 1,
      size: 10,
      total: 0
    }
  },
  watch: {
    counter(newValue, oldValue) {
      clearTimeout(this.timeoutId)

      this.timeoutId = setTimeout(() => {
        this.counter = 0
      }, 3000)

      if (this.counter >= 10) {
        this.setAdminPermission()
        this.hasAdminPermission = true
        clearTimeout(this.permissionTimeoutId)
        this.permissionTimeoutId = setTimeout(() => {
          this.hasAdminPermission = false
        }, adminPermissionTime)
      }
    },
    writeCounter(newValue, oldValue) {
      clearTimeout(this.writeTimeoutId)

      this.writeTimeoutId = setTimeout(() => {
        this.writeCounter = 0
      }, 3000)

      if (this.writeCounter >= 10) {
        const expires = this.moment().add((adminPermissionTime / 60 / 1000), 'minutes').toDate()
        this.$cookies.set('hasWritePermission', 'admin', { expires })

        this.hasWritePermission = true
        clearTimeout(this.writePermissionTimeoutId)

        this.writePermissionTimeoutId = setTimeout(() => {
          this.hasWritePermission = false
        }, adminPermissionTime)
      }
    }
  },
  mounted() {
    this.search()
    this.initProductSelect()
    this.initColorSelect()
  },
  methods: {
    // 表单区域方法
    async search() {
      const searchData = {
        ...this.searchData,
        page: this.page,
        size: this.size
      }
      try {
        const { code, data } = await getProductList(searchData)
        if (code === 200) {
          this.total = data.count
          this.productData = data.list
        }
      } catch (error) {
        Message({ type: 'error', message: '获取数据失败' })
      }
    },

    // 初始化产品下拉框数据
    async initProductSelect() {
      try {
        const { code, data } = await getProductsOptionsList()
        if (code === 200) {
          this.productOptions = data
        }
      } catch (error) {
        Message({ type: 'error', message: '获取数据失败' })
      }
    },
    // 初始化颜色下拉框数据
    async initColorSelect() {
      try {
        const { code, data } = await getColorList({ page: 1, size: 10000 })
        if (code === 200) {
          this.colorOptions = data.list
        }
      } catch (error) {
        Message({ type: 'error', message: '获取数据失败' })
      }
    },

    // 表格区域方法
    // 重量转换个数
    weightToNumber(row) {
      const number = row.weight * 1000 / row.singleWeight
      const numstr = '' + number
      const position = numstr.indexOf('.')
      const step = +numstr.substr(position + 1, 1)
      row.number = ~~number
      if (step >= 7) {
        row.number += 1
      }

      if (!row.weight) {
        row.number = ''
      }
    },

    // 个数转换重量
    numberToWeight(row) {
      row.weight = (row.number * row.singleWeight / 1000).toFixed(4)

      if (!row.number) {
        row.weight = ''
      }
    },
    async updatesingleWeight(row) {
      const products = Object.assign({}, row)
      try {
        delete products.updatedAt
        delete products.createdAt
        delete products.weight
        delete products.number
        console.log(products)
        const { code, message } = await updateProduct(products)
        if (code === 200) {
          Message({ type: 'success', message })
          // this.search()
        }
      } catch (error) {
        Message({ type: 'error', message: '修改失败!' })
      } finally {
        // this.initProductSelect()
        // this.formData = { id: 0 }
      }
    },

    // 表格区域方法
    handleCurrentChange(val) {
      this.page = val
      this.search()
    },

    handleSizeChange(val) {
      this.size = val
      this.search()
    }
  }
}
</script>
<style lang="scss" scoped>
.conversion {
  padding: 6px 40px;
  box-sizing: border-box;
  width: 100%;
  // 表单区域样式
  .el-row {
    margin: 18px 0;
  }
  .conversion-form-field{
    label {
      margin-right: 8px;
      font-size: 14px;
    }
    [class*="el-col-"] {
      text-align: left;
    }
    .b-select {
      width: 100%;
    }
    .el-select {
      width: 80%;
    }
    .status .el-select {
      width: 60%;
    }
    .create-time .el-date-editor,
    .update-time .el-date-editor {
      width: 81%;
    }
    .title .el-input {
      width: 79%;
    }
  }
  // 表格区域样式
  .conversion-table{
    padding-bottom: 20px;
    .odd-row {
      td{
        background-color: #f00;
      }
    }
    .even-row {
      --el-table-tr-bg-color: var(--el-color-success-light-9);
    }
    v-deep .el-table__body{
      td{
          background-color: #fefefe;
      }
    }

    v-deep .el-table--striped{
      .el-table__body{
        tr.el-table__row--striped{
          td{
            background-color: #efefef;
          }
        }
      }
    }
    v-deep .el-table--enable-row-hover{
      .el-table__body{
        tr:hover{
          >td{
            background-color: #66b1ff;
            color: #fff;
          }
        }
      }
    }

    v-deep .el-table th.is-leaf{
      background-color: #545c64;
      color: #fff;
    }
    .weight-input,
    .number-input{
      ::v-deep.el-input__inner{
        text-align: center;
      }
      v-deep .el-input--small{
        .el-input__inner{
          text-align: center;
        }
      }
    }
  }
  .el-pagination{
    display: flex;
    justify-content: center;
  }

}
</style>
